﻿using Microsoft.AspNetCore.Http;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace LJ.WebApi.Mvc.OpenApi.Filters;

public class FileUploadOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        //判断上传文件的类型，只有上传的类型是IFormCollection的才进行重写。
        if (context.ApiDescription.ActionDescriptor.Parameters.Any(w => w.ParameterType == typeof(IFormFile)))
        {
            var parameters = context.ApiDescription.ActionDescriptor.Parameters;
            Dictionary<string, OpenApiSchema> schema = new()
            {
                [parameters[0].Name] = new OpenApiSchema
                {
                    Description = "请选择文件",
                    Type = "string",
                    Format = "binary"
                }
            };
            Dictionary<string, OpenApiMediaType> content = new()
            {
                ["multipart/form-data"] = new OpenApiMediaType
                {
                    Schema = new OpenApiSchema { Type = "object", Properties = schema }
                }
            };
            operation.RequestBody = new OpenApiRequestBody() { Content = content };
        }
    }
}